package com.fengpb.friday.conductor.client.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fengpb.friday.conductor.cache.CacheKeyEnum;
import com.fengpb.friday.conductor.common.metadata.workflow.WorkflowDef;
import com.fengpb.friday.conductor.dao.MetadataDAO;
import com.fengpb.friday.conductor.service.CacheRefreshService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MetadataService {

    private static final Logger log = LoggerFactory.getLogger(MetadataService.class);

    private final MetadataDAO metadataDAO;

    private final ObjectMapper objectMapper = new ObjectMapper();

    private final CacheRefreshService refreshService;

    public MetadataService(MetadataDAO metadataDAO, CacheRefreshService refreshService) {
        this.metadataDAO = metadataDAO;
        this.refreshService = refreshService;
    }

    public void registerOrUpdateWorkflow(WorkflowDef def) {
        String name = def.getName();
        int version = def.getVersion();
        WorkflowDef current = metadataDAO.getWorkflowDef(name, version);
        try {
            if (current != null) {
                metadataDAO.updateWorkflowDef(def, version, objectMapper.writeValueAsString(def));
            } else {
                metadataDAO.registerWorkflowDef(def, version, objectMapper.writeValueAsString(def));
            }
            // 新建或修改后刷新缓存
            refreshService.pushCacheRefreshSignal(CacheKeyEnum.local_workflow_def_cache.name()
                    , CacheKeyEnum.local_workflow_def_cache.key(name, version));
        } catch (JsonProcessingException e) {
            log.error("register or update workflow error:{}", e.getMessage(), e);
        }
    }

    public List<WorkflowDef> getWorkflowDefList() {
        return metadataDAO.getAllWorkflowDef();
    }
}
